package org.example.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.commmon.BaseContext;
import org.example.commmon.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 实现登陆的拦截器
 *
 * 实现Filter接口 并重写其中的方法doFilter()
 */

@Slf4j

//这个注解用来拦截请求 并配置拦截路径
@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器对象  支持通配符
    public  static final AntPathMatcher ANT_PATH_MATCHER=new AntPathMatcher();

    /**
     * 将可以放行的路径和当前请求路径匹配
     * @param urls
     * @param requestUri
     * @return
     */
    public  boolean checkIfMatch(String[] urls,String requestUri){
        boolean flag=false;
        for (String url:urls){
            flag = ANT_PATH_MATCHER.match(url, requestUri);
            if (flag) return true;
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //先将请求抢转为httpservletRequest/response
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;
//        log.info("拦截到了请求uri:{}",req.getRequestURI());

        //获取请求的uri
        String requestUri=req.getRequestURI();
//        System.out.println("reqUri");
        //定义路径（不需要过滤的）
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",//静态资源

        };
        //判断路径是否匹配
        boolean match = checkIfMatch(urls, requestUri);
        if (match){
            filterChain.doFilter(req,resp);
            log.info("路径合法，放行");
            return;
        }


        /**
         * 不匹配的情况下，需要拦截
         */

        //如果已经登陆 直接放行
        Long operatorId = (Long) req.getSession().getAttribute("vip");
        /**
         * 此时将操作员的id设置到线程中
         */
        BaseContext.setCurrentId(operatorId);

        if (operatorId!=null) {
            filterChain.doFilter(req,resp);
            log.info("已经登陆,放行");
            return;
        }

        //如果未登陆 则返回未登陆的结果 通过输出流方式向客户端页面响应数据
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("拦截成功");


    }


}
